package com.study.testSpringBoot.mina.springBoot;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.study.testSpringBoot.mina.MinaServerHandler;

@Configuration
public class ConfigMina {

	/**
	 * 配置mina的多线程过滤器
	 * @return
	 */
	@Bean
	public ExecutorFilter executorFilter() {
		//设置初始化线程数，最大线程数
		ExecutorFilter executorFilter = new ExecutorFilter(10,20);
		return executorFilter;
	}
	
	/**
	 * 配置mina的转码过滤器
	 * @return
	 */
	@Bean
	public ProtocolCodecFilter protocolCodecFilter() {
		TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"), 
				LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());
		ProtocolCodecFilter pcf = new ProtocolCodecFilter(factory);
		return pcf;
	}
	
	/**
	 * 配置mina的日志过滤器
	 * @return
	 */
	@Bean
	public LoggingFilter loggingFilter() {
		return new LoggingFilter();
	}
	
	/**
	 * 将过滤器注入到mina的链式管理器中
	 * @return
	 */
	@Bean
	public DefaultIoFilterChainBuilder defaultIoFilterChainBuilder() {
		DefaultIoFilterChainBuilder def = new DefaultIoFilterChainBuilder();
		def.addLast("executor", executorFilter());
		def.addLast("logger", loggingFilter());
		def.addLast("protocol", protocolCodecFilter());
		return def;
	}
	
	/**
	 * 开启mina的server服务，并设置对应的参数
	 * @return
	 * @throws IOException
	 */
	@Bean
	public IoAcceptor ioAcceptor() throws IOException {
		IoAcceptor nio = new NioSocketAcceptor();
		//设置缓冲区大小
		nio.getSessionConfig().setReadBufferSize(2048);  
		//设置空闲状态时间，10秒没操作就进入空闲状态
		nio.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);  
		nio.setFilterChainBuilder(defaultIoFilterChainBuilder());
		nio.setHandler(new MinaServerHandler());
		nio.bind(new InetSocketAddress(9123));
		return nio;
	}
}
